import { defineStore, getActivePinia } from 'pinia'
import { ref } from 'vue'
import { removeToken, setUser } from '@/utils/auth'
import { getLogin, refreshTokenApi, getUserInfo } from '@/api/user'
export const useUserStore = defineStore('user', () => {
  const userInfo = ref({
    avatar: '',
    // 用户名
    username: '',
    // 昵称
    nickname: '',
    // 页面级别权限
    roles: [],
    // 按钮级别权限
    permissions: [],
    // 是否勾选了登录页的免登录
    isRemembered: false,
    // 登录页的免登录存储几天，默认7天
    loginDay: 7
  })
  const handRefreshToken = (data: Recordable) => {
    return new Promise((resolve, reject) => {
      refreshTokenApi(data)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  const login = (data: Recordable) => {
    return new Promise((resolve, reject) => {
      getLogin(data)
        .then((res) => {
          setUser(res.accessToken)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  } // 获取并设置用户信息
  const setUserInfo = () => {
    return new Promise<void>((resolve, reject) => {
      getUserInfo()
        .then((data: any) => {
          userInfo.value = { ...userInfo.value, ...data }
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  const resetPinia = () => {
    const getActive: any = getActivePinia()
    const stores = getActive._s // 获取所有 storen
    stores.forEach((item: any) => {
      try {
        item.$reset() // 重置每个 store 的状态
      } catch {}
    })
    removeToken()
  }

  return { userInfo, handRefreshToken, login, setUserInfo, resetPinia }
})
